const qiniu = require('qiniu');

module.exports.token = async (ctx, next) => {
   try {
      ctx.fsCache = ctx.fsCache || {}
      if (ctx.fsCache.qiniuToken) {
         if (Date.now() < ctx.fsCache.qiniuToken.expire) {
            ctx.status = 200;
            ctx.body = ctx.fsCache.qiniuToken.token
            return
         }
      }

      const { qiniu: qiniuConfig } = ctx.config
      let mac = new qiniu.auth.digest.Mac(qiniuConfig.ak, qiniuConfig.sk);
      let putPolicy = new qiniu.rs.PutPolicy({
         scope: qiniuConfig.bkt
      });
      let token = putPolicy.uploadToken(mac);
      ctx.fsCache.qiniuToken = {
         token,
         expire: Date.now() + 3200 * 1000
      }
      ctx.status = 200;
      ctx.body = token
   } catch (error) {
      ctx.logger.log(error)
      ctx.status = 400;
      ctx.body = {
         message: typeof error == 'string' ? error : '获取七牛Token失败'
      }
   }
}
